import re

from django import forms

from accounts.models import User, UserProfile


class LoginForm(forms.Form):
    '''登录表单'''
    username = forms.CharField(label="用户名", max_length=128, initial="请输入用户名")
    password = forms.CharField(label="密码", max_length=256, min_length=6,
                               widget=forms.PasswordInput)


    def clean_username(self):
        '''验证用户名'''
        username = self.cleaned_data['username']
        pattern = r'^1[0-9]{10}$'
        if not re.search(pattern, username):
            raise forms.ValidationError('请输入正确的手机号码')

        return username

    def clean(self):
        data = super().clean()
        username = data.get('username', None)
        password = data.get('password', None)
        err_list=[]
        if username and password:
            # 查询用户名和密码匹配的用户
            user_list = User.objects.filter(username = username)
            if user_list.count() == 0:
                err_list.append(forms.ValidationError('用户名不存在'))
            #验证密码是否正确
            if user_list.filter(password = password).count() == 0:
                err_list.append(forms.ValidationError('密码不正确'))
            if err_list:
                raise forms.ValidationError(err_list)

        return data




class UserEditForm(forms.Form):
    '''用户信息维护'''
    SEX_CHOICES = (
        ('1', '男'),
        ('0', '女'),
    )
    username = forms.CharField(label="用户名", max_length=128, initial="请输入用户名")
    email = forms.EmailField(label="邮箱", max_length=200, initial="请输入邮箱")
    age = forms.IntegerField(label="年龄")
    sex = forms.ChoiceField(label="性别", choices=SEX_CHOICES,
                            widget=forms.RadioSelect, initial='0')
    birth_date = forms.DateField(label="生日")
    avatar = forms.ImageField(label='用户头像')

class UserRegForm(forms.Form):
    '''用户注册表单'''
    username = forms.EmailField(label="用户名", max_length=200)
    password = forms.CharField(label="密码", max_length=256,
                               widget=forms.PasswordInput)
    nickname = forms.CharField(label="昵称", max_length=128, min_length=2)
    birth_date = forms.DateField(label="生日", required=False)

class TestForm(forms.Form):
    '''练习题-表单练习'''
    name = forms.CharField(label="我的姓名", max_length=200, min_length=2)
    age = forms.IntegerField(label="我的年龄", required=False)
    grag = forms.CharField(label="毕业院校", max_length=200, min_length=4)
    email = forms.EmailField(label="电子邮箱", max_length=200)
    intro = forms.CharField(label="自我介绍", widget=forms.Textarea)
    pers = forms.CharField(label="个性签名", max_length=200, initial='网页开发')

    avatar = forms.ImageField(label='上传头像', required=False)

class PasConfirm(forms.Form):
    '''练习题-验证密码一致性'''
    password = forms.CharField(label="密码", max_length=256, min_length=6,
                               widget=forms.PasswordInput)
    pasconfirm = forms.CharField(label="确认密码", max_length=256, min_length=6,
                               widget=forms.PasswordInput)

    def clean_password(self):
        '''验证密码（必须由数字、字母、下划线构成）'''
        password = self.cleaned_data['password']
        pattern = r'^.*(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[_])\w{6,}'
        # pattern = r'^[a-zA-Z0-9_]{6,}'
        if not re.search(pattern, password):
            raise forms.ValidationError('密码必须由数字、字母、下划线构成，长度不少于6位')
        return password

    def clean(self):
        data = super().clean()
        if self.errors:
            return
        password = data['password']
        pasconfirm = data['pasconfirm']

        if password and pasconfirm:
            # 验证两次输入密码是否一致
            if password != pasconfirm:
                raise forms.ValidationError('两次密码输入不一致')

        return data

# 从ORM模型创建表单
class UserChangeForm(forms.ModelForm):
    '''用户基本信息修改'''
    class Meta:
        model = User
        # fields = ('username', 'password', 'nickname', 'avatar')
        exclude = ('status',)
        labels = {
            'username': '手机号码'
        }
        widgets = {
            'password': forms.PasswordInput
        }

    def clean_username(self):
        '''验证用户名'''
        username = self.cleaned_data['username']
        pattern = r'^1[0-9]{10}$'
        if not re.search(pattern, username):
            raise forms.ValidationError('手机号码%s输入不正确', params=(username))

        return username

    def save(self, commit=False):
        user_obj = super().save(commit)
        user_obj.save()
        UserProfile.objects.create(user=user_obj, username=user_obj.username)
        return user_obj

class AvatarUploadForm(forms.Form):
    '''用户头像上传'''
    avatar = forms.ImageField(label='用户头像')

